#define _CRT_SECURE_NO_WARNINGS 1
#include"DTree.h"
#include"Queque.h"
BTNode* BinaryTreeCreate(BTDataType* a, int* pi)
{
	if (a[*pi] == '#')
	{
		(*pi)++;
		return NULL;
	}
	BTNode* root = (BTNode*)malloc(sizeof(BTNode));
	assert(a);
	root->date = a[(*pi)++];
	root->left = BinaryTreeCreate(a, pi);
	root->right = BinaryTreeCreate(a, pi);
	return root;
}
void BinaryTreeDestory(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	if (root->left == NULL && root->right == NULL)
	{
		free(root);
		root = NULL;
		return;
	}
	BinaryTreeDestory(root->left);
	BinaryTreeDestory(root->right);
	free(root);
	root = NULL;
}
int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return  BinaryTreeSize(root->left) + BinaryTreeSize(root->right) + 1;
}
int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}
int BinaryTreeLevelKSize(BTNode* root, int k)
{
	assert(k > 0);
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->date == x)
	{
		return root;
	}
	BTNode* str1 = BinaryTreeFind(root->left, x);
	if (str1)
	{
		return str1;
	}
	BTNode* str2 = BinaryTreeFind(root->right, x);
	if (str2)
	{
		return str2;
	}
}
void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}
	printf("%c ", root->date);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}
void BinaryTreeInOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}
	BinaryTreeInOrder(root->left);
	printf("%c ", root->date);
	BinaryTreeInOrder(root->right);
}
void BinaryTreePostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}
	BinaryTreePostOrder(root->left);
	BinaryTreePostOrder(root->right);
	printf("%c ", root->date);
}
void BinaryTreeLevelOrder(BTNode* root)
{
	assert(root);
	Queque q;
	QuequeInit(&q);
	Quequepush(&q, root);
	while (!QuequeEmpty(&q))
	{
		BTNode* front = Quequefront(&q);
		Quequepop(&q);
		printf("%c ", front->date);
		if (front->left)
		{
			Quequepush(&q, front->left);
		}
		if (front->right)
		{
			Quequepush(&q, front->right);
		}
	}
	printf("\n");
}
bool BinaryTreeComplete(BTNode* root)
{
	assert(root);
	Queque q;
	QuequeInit(&q);
	Quequepush(&q, root);
	while (!QuequeEmpty(&q))
	{
		BTNode* front = Quequefront(&q);
		Quequepop(&q);
		if (front == NULL)
		{
			break;
		}
		Quequepush(&q, front->left);
		Quequepush(&q, front->right);
	}
	while (!QuequeEmpty(&q))
	{
		BTNode* front = Quequefront(&q);
		Quequepop(&q);
		if (front)
		{
			Quequedestroy(&q);
			return false;
		}
	}
	Quequedestroy(&q);
	return true;
}





